package com.masterclient.app.modules.main;

import android.content.Intent;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.os.Bundle;
import android.os.CountDownTimer;
import android.os.Handler;
import android.support.annotation.Nullable;
import android.support.v4.view.ViewPager;
import android.text.TextUtils;
import android.view.View;
import android.view.animation.AlphaAnimation;
import android.widget.ImageView;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.bumptech.glide.Glide;
import com.bumptech.glide.util.Util;
import com.eoner.baselib.utils.sp.SPUtils;
import com.eoner.common.BuildConfig;
import com.eoner.common.config.Config;
import com.eoner.managerlibrary.netsign.NetEnvManager;
import com.eoner.managerlibrary.system.SystemConfigStorage;
import com.eoner.managerlibrary.system.callback.SystemConfigCallBack;
import com.eoner.managerlibrary.user.UserDataManager;
import com.eoner.middlelib.eventbus.EventBusManager;
import com.masterclient.app.BaseActivity;
import com.masterclient.app.MainActivity;
import com.masterclient.app.R;
import com.gyf.immersionbar.ImmersionBar;
import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import pl.droidsonroids.gif.GifImageView;

/**
 * 作者：sean
 * 创建时间：2017/8/14 19:57
 * 功能说明：
 */
public class SplashActivity extends BaseActivity {
    @BindView(R.id.iv_load)
    ImageView ivLoad;
    @BindView(R.id.tv_time)
    TextView tvTime;
    @BindView(R.id.rl_load)
    RelativeLayout rlLoad;
    @BindView(R.id.iv_splash)
    GifImageView ivSplash;

    @BindView(R.id.splash_layout)
    View splash_layout;
    @BindView(R.id.guide_layout)
    View guide_layout;

    @BindView(R.id.vp)
    ViewPager vp;
    @BindView(R.id.rb1)
    RadioButton rb1;
    @BindView(R.id.rb2)
    RadioButton rb2;
    @BindView(R.id.rb3)
    RadioButton rb3;
    @BindView(R.id.rb4)
    RadioButton rb4;
    @BindView(R.id.rg)
    RadioGroup rg;
    int[] images = {R.mipmap.yindao1, R.mipmap.yindao2, R.mipmap.yindao3, R.mipmap.yindao3};


    private CountDownTimer timer;
    private long timeStart, startTime;
    private Handler handler = new Handler();

    //测试代码提交
    int versioncode;
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_splash);
        ButterKnife.bind(this);

        //记住上次选择环境代码 上线代码一定要注释掉
        if (BuildConfig.ISENV) {
            String base_url = SPUtils.getInstance().getString(NetEnvManager.BASE_URL_KEY);
            if (!TextUtils.isEmpty(base_url)) {
                NetEnvManager.BASE_URL = base_url;
            }

            String base_surl = SPUtils.getInstance().getString(NetEnvManager.BASE_SURL_KEY);
            if (!TextUtils.isEmpty(base_surl)) {
                NetEnvManager.BASE_SURL = base_surl;
            }

            String base_rurl = SPUtils.getInstance().getString(NetEnvManager.BASE_RURL_KEY);
            if (!TextUtils.isEmpty(base_rurl)) {
                NetEnvManager.BASE_R_URL = base_rurl;
            }

            String gzg_test_user = SPUtils.getInstance().getString(Config.GZG_TEST_USER_KEY);
            if (!TextUtils.isEmpty(gzg_test_user)) {
                Config.GZG_TEST_USER = gzg_test_user;
            }
        }

        ImmersionBar.with(this).statusBarDarkFont(true, 0.2f).transparentStatusBar().init();

        if (!this.isTaskRoot()) { // 当前类不是该Task的根部，那么之前启动
            Intent intent = getIntent();
            if (intent != null) {
                String action = intent.getAction();
                if (intent.hasCategory(Intent.CATEGORY_LAUNCHER) && Intent.ACTION_MAIN.equals(action)) { // 当前类是从桌面启动的
                    finish(); // finish掉该类，直接打开该Task中现存的Activity
                    return;
                }
            }
        }

        startTime = System.currentTimeMillis();

        PackageInfo packageInfo = null;
        try {
            packageInfo = getPackageManager().getPackageInfo(getPackageName(), 0);
        } catch (PackageManager.NameNotFoundException e) {
            e.printStackTrace();
        }
        versioncode = packageInfo.versionCode;
        if (!SPUtils.getInstance().getBoolean(Config.APP_PRIVACY_UPDATE_VERSION, false)) {
            new PrivacyDialog(this, new PrivacyDialog.AgreementPrivacy() {
                @Override
                public void onAgreement() {
                    EventBusManager.post(EventBusManager.createAgreePrivacyEvent());
                    getSystemConfig();
                    if (isTimer != 1) {
                        startActivity();
                    }
                }
            }).show();
        } else {
            EventBusManager.post(EventBusManager.createAgreePrivacyEvent());
            getSystemConfig();
        }
    }

    private void getSystemConfig() {
        timeStart = System.currentTimeMillis();
        SystemConfigStorage.getInstance().getSystemConfig(new SystemConfigCallBack() {
            @Override
            public void onSuccess() {
                onFailStart();
            }

            @Override
            public void onFailed(String errMsg) {
                if (SPUtils.getInstance().getBoolean(Config.APP_PRIVACY_UPDATE_VERSION, false)) {
                    showActivity();
                }
                tvTime.setVisibility(View.GONE);
            }
        });
    }

    @Override
    protected void onStart() {
        super.onStart();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (Util.isOnMainThread() && !this.isFinishing()) {
            Glide.with(getApplicationContext()).pauseRequests();
        }
        if (timer != null) {
            timer.cancel();
        }
    }

    private void onFailStart() {
        int remian = (int) (2000 - (System.currentTimeMillis() - timeStart));
        if (remian > 0) {
            rlLoad.postDelayed(new Runnable() {
                @Override
                public void run() {
                    startActivity();
                }
            }, remian);
        } else {
            startActivity();
        }
    }


    private int isTimer = 0;

    private void showActivity() {
        isTimer = 1;
        AlphaAnimation animation = new AlphaAnimation(0.0f, 1);
        animation.setDuration(300);
        rlLoad.startAnimation(animation);
        rlLoad.setVisibility(View.VISIBLE);
        timer = new CountDownTimer(3100, 1000) {
            @Override
            public void onTick(long lll) {
                tvTime.setText((int) Math.floor(lll / 1000) + "s 跳过");
            }

            @Override
            public void onFinish() {
                isTimer = 2;
                tvTime.setText("0s 跳过");
                rlLoad.setVisibility(View.GONE);
                if (splash_layout.getVisibility() == View.VISIBLE) {
                    startActivity();
                }
            }
        };
        timer.start();
    }

    private void startActivity() {
        if (UserDataManager.getInstance().isUserDisable()) {
            //TODO:清除用户信息
            UserDataManager.getInstance().clearLoginInfo();
        }
        startActivity(new Intent(SplashActivity.this, MainActivity.class));
        finish();
    }

    @OnClick({R.id.tv_time, R.id.iv_splash})
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.tv_time:
                timer.cancel();
                startActivity();
                break;
            case R.id.iv_splash:
                String target = SystemConfigStorage.getInstance().getAppStartInfo().getTarget();
                String target_id = SystemConfigStorage.getInstance().getAppStartInfo().getTarget_id();
                if (!TextUtils.isEmpty(target)) {// && !TextUtils.isEmpty(target_id)
                    if (timer != null) {
                        timer.cancel();
                    }
                    Intent intent = new Intent(SplashActivity.this, MainActivity.class);
                    intent.putExtra("target", target);
                    intent.putExtra("target_id", target_id);
                    startActivity(intent);
                    finish();
                }
                break;
        }
    }
}
